package com.example.rxjavaandretrofitdemo;

import android.content.Context;

import rx.Subscriber;

/**
 *
 * @author tangjiangxu
 * @date 11/23/17
 */

public class ProgressSubscriber extends Subscriber implements ProgressCancelListener {

    private SubscriberOnNextListener mSubscriberOnNextListener;
    private Context context;
    private ProgressDialogHandler mProgressDialogHandler;

    public ProgressSubscriber(SubscriberOnNextListener mSubscriberOnNextListener, Context context) {
        this.mSubscriberOnNextListener = mSubscriberOnNextListener;
        this.context = context;
        mProgressDialogHandler = new ProgressDialogHandler(context, this, true);
    }

    @Override
    public void onStart() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    @Override
    public void onCompleted() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
        }
    }

    @Override
    public void onError(Throwable e) {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
        }
    }

    @Override
    public void onNext(Object o) {
        if (mSubscriberOnNextListener != null) {
            mSubscriberOnNextListener.onNext(o);
        }
    }

    @Override
    public void onCanelProgress() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }

    /**
     * 自定以ProgressSubscriber中onNext方法后续回调的接口
     */

    public interface SubscriberOnNextListener<T> {
        void onNext(T t);
    }


}
